package com.abbas.smartCity.retroft

import android.widget.Toast
import com.abbas.CayTcore.CoreApp
import com.abbas.CayTcore.entity.NetBean
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.net.UnknownServiceException

/**
 * @param <T> 请求的数据类型</T>
 */
abstract class ICallback2<T> : Callback<NetBean<T>> {
    override fun onResponse(call: Call<NetBean<T>>, response: Response<NetBean<T>>) {
        CoreApp.handler.post {
            if (!response.isSuccessful) {
                onServerError()
            } else {
                response.body()?.let {
                    if (it.code in 200..299) {
                        onSuccess(call, it)
                    } else {
                        onRequestError(call, it.msg)
                    }
                } ?: onRequestError(call, "响应体为空")
            }
        }
    }

    override fun onFailure(call: Call<NetBean<T>>, throwable: Throwable) {
        when(throwable){
            is UnknownServiceException ->
                onServerError()
            else ->
                onServerError()
        }
    }

    /**
     * 数据访问成功后的回调
     *
     * @param call Call
     * @param data 数据
     */
    abstract fun onSuccess(call: Call<NetBean<T>>, data: NetBean<T>)

    open fun onServerError() {
        CoreApp.handler.post {
            Toast.makeText(CoreApp.context, "网络出现问题，请检查网络", Toast.LENGTH_SHORT).show()
        }
    }

    open fun onRequestError(call: Call<NetBean<T>>, msg: String) {
        CoreApp.handler.post {
            Toast.makeText(CoreApp.context, msg, Toast.LENGTH_SHORT).show()
        }
    }

}